import React, { useState } from 'react';
import { 
  Container, 
  Typography, 
  TextField, 
  Button, 
  Snackbar, 
  MenuItem, 
  Box, 
  CircularProgress 
} from '@mui/material';
import { createAndBroadcastNotification } from '@/apis/notification';

const AdminNotification = () => {
  const [content, setContent] = useState('');
  const [type, setType] = useState('SYSTEM');
  const [snackbar, setSnackbar] = useState({ open: false, message: '', severity: 'success' });
  const [isLoading, setIsLoading] = useState(false);

  
  const handleSubmit = async (e) => {
    e.preventDefault();
    setIsLoading(true);
    try {
      await createAndBroadcastNotification(content, type);
      setSnackbar({ open: true, message: '通知发送成功', severity: 'success' });
      setContent('');
      setType('SYSTEM');
    } catch (error) {
      setSnackbar({ open: true, message: '发送失败: ' + (error.message || '未知错误'), severity: 'error' });
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <Container maxWidth="md">
      <Typography variant="h4" component="h1" gutterBottom>
        发送通知
      </Typography>
      <form onSubmit={handleSubmit}>
        <TextField
          fullWidth
          label="通知内容"
          value={content}
          onChange={(e) => setContent(e.target.value)}
          margin="normal"
          required
          multiline
          rows={4}
          disabled={isLoading}
        />
        <TextField
          select
          fullWidth
          label="通知类型"
          value={type}
          onChange={(e) => setType(e.target.value)}
          margin="normal"
          required
          disabled={isLoading}
        >
          <MenuItem value="SYSTEM">系统通知</MenuItem>
          <MenuItem value="PROMOTION">促销通知</MenuItem>
          <MenuItem value="ORDER">订单通知</MenuItem>
        </TextField>
        <Box mt={2}>
          <Button 
            type="submit" 
            variant="contained" 
            color="primary" 
            disabled={isLoading}
            startIcon={isLoading ? <CircularProgress size={20} /> : null}
          >
            {isLoading ? '发送中...' : '发送通知'}
          </Button>
        </Box>
      </form>
      <Snackbar
        open={snackbar.open}
        autoHideDuration={3000}
        onClose={() => setSnackbar({ ...snackbar, open: false })}
        message={snackbar.message}
        // 你可以根据 severity 来设置不同的样式
      />
    </Container>
  );
};

export default AdminNotification;